<template>
	<div class="tpl-list">
		<curr-app :left="245"></curr-app>
		<list-title :data="header" @changeVisible="changeVisible"></list-title>
		<div style="padding: 20px 0">
			<div class="noapp disabled" v-if="!tplList"><span class="el-icon-warning"></span>暂无应用</div>
			<el-row>
				<el-col :span="4" v-for="(item, index) in tplList" :key="index" style="position: relative">
					<el-card :body-style="{ padding: '10px' }">
						<tag color="error" class="tag_small notsys" v-if="item.systpl == 1" style="cursor: default" title="自定义模版">自定义模版</tag>
						<tag color="error" class="tag_small sys" v-if="item.systpl == 2" style="cursor: default" title="系统模版">系统模版</tag>
						<div ref='photobox' class="photobox">
							<span class="icon iconfont icon-nopic" v-if="!item.preview"></span>
							<img :src="item.preview" class="image" v-if="item.preview">
						</div>
						<div style="padding: 0px;">
							<div class="bottom clearfix">
								<!-- 注释原因：不需要分模版语言了 -->
								<!-- <span :title="getLangname(item.lang)">
									<svg class="icon svg-icon" style="width: 21px; height:15px; z-index: 1; border:solid 1px #f0f0f0; vertical-align: middle" aria-hidden="true">
										<use :xlink:href="'#icon-' + ((item.lang.indexOf('-') != -1)?item.lang.substr(0, 2):item.lang)"></use>
									</svg>
								</span> -->
								<tag color="error" class="tag_small color_red" v-if="item.isdefault == 2" style="cursor: default" title="默认模版">默认</tag>
								<time class="time">{{ item.tplname }}</time>
								<el-button type="primary" class="button" @click="handleEdit(item)">编辑</el-button>
								<el-button type="success" class="button" style="margin-right: 2px" @click="list(index, item)">列表</el-button>
							</div>
						</div>
					</el-card>
				</el-col>
			</el-row>
		</div>
		<!-- 添加模版 开始 -->
		<el-dialog :title="dialogTitle" :visible.sync="header.dialogs[0].visible" :close-on-click-modal="false" width="550px">
			<el-form :model="tplForm" :rules="rules" ref="tplForm" label-width="100px">
				<el-form-item label="模版名称" prop="data.tplname" style="width: 468px;">
					<el-input v-model="tplForm.data.tplname" placeholder="模版名称" maxlength="5" show-word-limit></el-input>
				</el-form-item>
				<!-- 注释原因：不需要考虑语言了 -->
				<!-- <el-form-item label="选择语言" prop="data.lang">
					<el-select v-model="tplForm.data.lang" placeholder="请选择语言">
						<el-option v-for="(item, index) in lang" :key="index" :label="item.label" :value="item.value">
							<svg class="icon svg-icon" style="width: 25px; height: 15px; float: left; margin: 10px 15px 0 0; overflow: hidden" aria-hidden="true">
								<use :xlink:href="'#icon-' + item.flag"></use>
							</svg>
							<span style="float: left">{{ item.label }}</span>
						</el-option>
					</el-select>
				</el-form-item> -->
				<el-form-item label="预览图" prop="data.preview" style="width: 173px;">
					<upload-oss 
					:stsdomain="this.$domain.ac" 
					:ossdomain="this.$ossdomain" 
					:appid="$route.query.appid" 
					:limit="1" 
					:fileList="tplForm.data.preview" 
					:maxSize="20" 
					@insertFile="insertFile"
					@delFile="delFile">
					</upload-oss>
				</el-form-item>
				<el-form-item label="更新方式" prop="data.updataflag" v-show="tplForm.data.id == 0">
					<template>
						<el-radio v-model="tplForm.data.updataflag" label="1">本地上传</el-radio>
						<el-radio v-model="tplForm.data.updataflag" label="2">GIT仓库更新</el-radio>
					</template>
				</el-form-item>
				<!-- 隐藏注释：模版经过git更新，不需要通过前端上传了 -->
				<el-form-item label="模版上传" prop="data.tplfolder" style="width: 468px;" v-show="tplForm.data.updataflag == 1">
					<el-upload
					ref="upload"
					class="upload-demo"
					drag
					multiple
					name="UploadForm[file]"
					:with-credentials="true"
					accept=".zip"
					:limit="1"
					:on-exceed="handleExceed"
					:on-success="handleSuccess"
					:on-remove="handleRemove"
					:action="$domain.cms + '/' + $api.addTplInfo + '?appid=' + $route.query.appid + '&id=' + tplForm.data.id"
					:auto-upload="true">
					<i class="el-icon-upload"></i>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<div class="el-upload__tip" slot="tip">仅支持上传ZIP格式压缩包</div>
					</el-upload>
				</el-form-item>
				<el-form-item label="GIT地址" prop="data.gitadd" style="width: 468px;" v-show="tplForm.data.updataflag == 2">
					<el-input type="textarea" :rows="3" placeholder="请输入GIT地址" v-model="tplForm.data.gitadd"></el-input>
					<p class="help">仓库地址必须为公开地址，仅支持GIT</p>
					<p class="orange" v-if="tplForm.data.id>0">注意：如仓库已克隆过，此参数修改无效</p>
				</el-form-item>
				<el-form-item label="文件夹嵌套" prop="data.folder" style="width: 468px;">
					<el-input v-model="tplForm.data.folder" placeholder="如：website/en/"></el-input>
					<p class="help">当模版被文件夹嵌套时，需写出具体路径，否则找不到模版</p>
				</el-form-item>
				<el-form-item label="是否默认" prop="data.isdefault">
					<el-switch v-model="tplForm.data.isdefault"></el-switch>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="header.dialogs[0].visible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm('tplForm')" :disabled='tplForm.submitLock'>
					确 定 <span class="el-icon-loading" v-if='tplForm.submitLock'></span>
				</el-button>
			</div>
		</el-dialog>
		<!-- 上传模版 结束 -->
	</div>
	</div>
</template>

<script>
import ListTitle from "pc/common/Title"
import UploadOss from "pc/common/UploadOss"
import {changeToBool, judgeAuth} from "static/js/common.js"
import {mapGetters} from 'vuex'
import {ERROR} from "static/js/constant.js"
import CurrApp from "pc/common/CurrApp"

export default {
	data() {
		var checkTplfolder = (rule, value, callback) => {
            if (this.tplForm.data.updataflag == 1 && !value) {
                return callback(new Error('请上传模版'));
            } else {
                callback();
            }
        };
        var checkGgitadd = (rule, value, callback) => {
            if (this.tplForm.data.updataflag == 2 && !value) {
                return callback(new Error('请输入模版地址'));
            } else {
                callback();
            }
        };
		return {
			/*appid*/
			appid: this.$route.query.appid,
			/*头部数据*/
			header: {
				title: '模版列表',
				reload: true,
				dialogs: [
					{
						title: '添加模版',
						type: 'primary',
						visible: false,
						auth: false,
					}
				]
			},
			dialogTitle: '添加模版',//dialog标题
			/*模版列表*/
			tplList: [
				// {
				// 	id: 1,
				// 	tplname: '默认模版',
				// 	lang: '',
				// 	preview: 'http://qh168.oss-cn-hangzhou.aliyuncs.com/ac/3_20200903182804.jpg?x-oss-process=style/300',
				// 	updataflag: 1,
				// 	tplfolder: '',
				// 	folder: '',
				// 	gitadd: '',
				// 	isdefault: 1,
				// 	systpl: 1,
				// },
				// {
				// 	id: 2,
				// 	tplname: '默认模版阿斯的',
				// 	lang: '',
				// 	preview: '',
				// 	updataflag: 2,
				// 	tplfolder: '',
				// 	folder: '',
				// 	gitadd: '',
				// 	isdefault: 2,
				//  systpl: 1,
				// }
			],
			/*上传模版数据*/
			tplForm: {
				submitLock: false,
				auth: false,//购买权限
				data: {
					id: 0,
					tplname: '',
					lang: '',
					preview: [],
					updataflag: '2',
					tplfolder: '',
					folder: '',
					gitadd: '',
					isdefault: false,
				}
			},
			rules: {
				data: {
					tplname: [
						{ required: true, message: '请输入模版名称', trigger: 'blur' },
						{ min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
					],
					tplfolder: [
                        { validator: checkTplfolder, trigger: 'blur' }
                    ],
                    gitadd: [
                        { validator: checkGgitadd, trigger: 'blur' }
                    ],
				}
			}
		};
	},
	components: {
		ListTitle,
		UploadOss,
		CurrApp
	},
	created: function() {
		/*权限判断显示*/
		this.header.dialogs[0].auth = (judgeAuth('tplinfoList', this.allMenuList) == undefined)?false:true
		/*取出语言列表*/
		// this.getLangList()
		/*取出模版信息列表数据*/
		this.getTplinfoList()
	},
	methods: {
		/*取出模版信息列表数据*/
		getTplinfoList: function(){
			if(this.$api.tplinfoList != undefined){
				this.$baseURL(this.$domain.cms)
				this.$get(this.$api.tplinfoList, this.$route.query).then(res => {
					// console.log(res.data.data);
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.tplList = []
							Object.keys(res.data.data).forEach((k) => {
								this.tplList.push ({
									id: res.data.data[k].id,
									tplname: res.data.data[k].tplname,
									lang: res.data.data[k].lang,
									preview: res.data.data[k].preview,
									updataflag: res.data.data[k].updataflag,
									tplfolder: res.data.data[k].tplfolder,
									folder: res.data.data[k].folder,
									gitadd: res.data.data[k].gitadd,
									isdefault: res.data.data[k].isdefault,
									systpl: res.data.data[k].systpl,
								});
							})
						}
					}
				})
				.catch(err => {
					let error = ERROR.SER404
					if(err.response != undefined  && err.response.status == 500){
						error = ERROR.SER500
					}
					this.$message({
						showClose: true,
						message: error,
						type: 'error'
					});
				})
				.finally(() => {
					this.tableLoading = false
				}) 
			}
		},
		/*取出语言列表*/
		getLangList: function(){
			if(this.$api.cmsLang != undefined){
				this.$baseURL(this.$domain.cms)
				this.$get(this.$api.cmsLang, this.$route.query).then(res => {
					// console.log(res.data.data);
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.lang = []
							Object.keys(res.data.data).forEach((k) => {
								this.lang.push ({
									value: res.data.data[k].value,
									flag: res.data.data[k].flag,
									label: res.data.data[k].label,
								});
							})
						}
					}
				})
				.catch(err => {
					let error = ERROR.SER404
					if(err.response != undefined  && err.response.status == 500){
						error = ERROR.SER500
					}
					this.$message({
						showClose: true,
						message: error,
						type: 'error'
					});
				})
				.finally(() => {}) 
			}
		},
		/*dialog切换 方便子组件调用*/
		changeVisible: function(index){
			this.dialogTitle = '添加模版'
			this.header.dialogs[index].visible = !this.header.dialogs[index].visible
			this.tplForm.data.id = 0
			this.tplForm.data.tplname = ''
			this.tplForm.data.lang = ''
			this.tplForm.data.preview = []
			this.tplForm.data.updataflag = '1'
			this.tplForm.data.tplfolder = ''
			this.tplForm.data.folder = ''
			this.tplForm.data.gitadd = ''
		},
		/*文件超出个数限制时的钩子 超过 limit - fileList.length 的值时触发, 主要是验证*/
		handleExceed(files, fileList) {
			this.$message.warning(`只能上传 1 个文件`);
		},
		/*文件列表移除文件时的钩子*/
		handleRemove(res, file, fileList) {
			this.tplForm.data.tplfolder = '';
		},
		/*上传成功后*/
		handleSuccess(res, file, fileList) {
			if(res.code == 0){
				this.tplForm.data.tplfolder = res.data
			}else{
				this.$message.warning(res.info);
			}
		},
		/*插入上传的文件*/
		insertFile(file){
			// console.log(file instanceof Array)
			if(file instanceof Array){//如果是数组的话，说明是图片
				for(let i=0; i<file.length; i++){
					this.tplForm.data.preview.push(
						{
							name: '',
							url:  file[i].url
						}
					)
				}
			}else{//单个文件路径

			}
		},
		/*删除上传的文件*/
		delFile(index){
			if(index >= 0){//图片
				this.tplForm.data.preview.splice(index, 1)
			}else{//文件路径

			}
		},
		/*提交添加、修改表单*/
		submitForm(formName) {
			if(!this.tplForm.submitLock){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.tplForm.submitLock = true;
						let apiUrl = this.$api.addTplInfo//默认是添加
						if(this.tplForm.data.id > 0){//修改
							apiUrl = this.$api.modifyTplInfo
						}
						/*添加*/
						this.$baseURL(this.$domain.cms)
						let data = JSON.parse(JSON.stringify(this.tplForm.data))

						this.$post(apiUrl, {
							appid: this.appid,
							Tplinfo: data,
						}).then(res => {
							// console.log(res);
							/*成功*/
							if(res.data.code == 0){
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'success'
								});
								if(this.tplForm.data.id > 0){
									this.header.dialogs[0].visible = false//显示修改的窗口
								}
								this.$refs[formName].resetFields();

								/*清除上传的模版*/
								this.$refs.upload.uploadFiles.splice(0, 1)
								this.tplForm.data.tplfolder = '';

								/*更新模版信息列表数据*/
								this.getTplinfoList()
							}else{
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'error'
								});
							}
							this.tplForm.submitLock = false;
						})
						.catch(err => {
							let error = ERROR.SER404
							if(err.response != undefined  && err.response.status == 500){
								error = ERROR.SER500
							}
							this.$message({
								showClose: true,
								message: error,
								type: 'error'
							});
						});
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*模版列表*/
		list(index, row){
			// console.log(row)
			this.$router.push(
				{
					name: 'pc/cms/instance/template/TplManage', 
					query: {
						appid: this.$route.query.appid,
						id: row.id,
						flag: row.updataflag
					}
				}
			)
		},
		/*编辑*/
		handleEdit: function(row) {
			// console.log(row)
			this.dialogTitle = '编辑模版信息'
			this.header.dialogs[0].visible = true//显示修改的窗口

			let preview = []
			if(row.preview != ''){
				preview = row.preview.split(',')
				for(let i=0; i<preview.length; i++){
					preview[i] = {
						name: '',
						url: preview[i]
					}
				}
			}
			this.tplForm.data.id = row.id
			this.tplForm.data.tplname = row.tplname
			this.tplForm.data.lang = row.lang
			this.tplForm.data.preview = preview
			this.tplForm.data.updataflag = row.updataflag
			this.tplForm.data.tplfolder = row.tplfolder
			this.tplForm.data.folder = row.folder
			this.tplForm.data.gitadd = row.gitadd
			this.tplForm.data.isdefault = changeToBool(row.isdefault)
		},
	},
	computed: {
		getLangname(val) {
			return function (val) {
				let langname = ''
				LANG.find((item) => {
					if(val == item.value){
						langname = item.label
					}
				})
				return (langname)
			}
		},
		...mapGetters([
			'allMenuList'
		])
	}
};
</script>

<style lang="stylus" scoped>
@import "../../../../../../static/css/variable.styl"
.tpl-list
	// height: 100%
	.loading
		width: 100%
		height: 100%
		padding-top: 80px
		text-align: center
		.el-icon-loading
			margin-right: 5px
	.noapp
		text-align: center
		.el-icon-warning
			margin-right: 5px
	h3
		text-align: center
		margin: 35px 0
		span
			display: block
			width: 30px
			margin: 8px auto 0
			padding: 1px 15px
			background: $theme-color
	.el-col
		width: 250px
		margin: 0 10px 15px
		.el-card
			width: 100%
			.time
				font-size: 13px
				color: #999
			.bottom
				margin-top: 13px
				line-height: 20px
				height: 20px
			.button 
				padding: 3px 8px
				float: right
			.photobox
				display: block
				width: 230px
				height: 230px
				position: relative
				.image
					max-height: 230px
					max-width: 230px
					display: block
					position: absolute
					margin-top: 50%
					margin-left: 50%
					transform: translateX(-50%) translateY(-50%)
				.image+div
					padding: 14px 0 5px !important
			.clearfix:before,.clearfix:after
				display: table
				content: ""
			.clearfix:after
				clear: both
.icon-nopic
	display: block
	width: 100%
	height: 100%
	padding-top: 33%
	color: #ebebeb
	font-size: 50px
	text-align: center
	box-sizing: border-box
	cursor: pointer
	position: relative
	
/deep/ .el-upload
	width: 100% !important
	.el-upload-dragger
		border-radius: 0px
		width: 100% !important
.notsys
	background: rgba(0, 0, 0, .3) !important
	position: absolute
	right: 0
	top: 6
	border: 0 !important
	z-index: 99
.sys
	background: red !important
	position: absolute
	right: 0
	top: 6
	border: 0 !important
	z-index: 99
.tag_small
	background: none
	border: #d22717 solid 1px
	border-radius: 0
	vertical-align: middle !important
	padding: 0 2px !important
	margin: 0 !important
	line-height: 12px !important
.color_red
	/deep/ .ivu-tag-color-white
		color: red !important
/deep/ .el-input__count
	position: static !important
</style>